"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const utils = require("utils");
const index = require("./handleRequest/index.js");
const index$1 = require("../const/index.js");
const db = uniCloud.database();
const collection = db.collection("token-valid");
async function getDbCache() {
  let [err, res] = await utils.util.awaitWrap(
    collection.where({
      "token-type": index$1.WifiFlowCookie
    }).limit(1).get()
  );
  if (err) {
    return [new utils.InsideErr(err), void 0];
  }
  let { data = [] } = res || {};
  return [void 0, data[0]];
}
async function updateCookie(cookie, docId) {
  if (docId) {
    await collection.doc(docId).update({
      valid: true,
      token: cookie,
      update: utils.util.baseDateDes(new Date())
    });
    return docId;
  } else {
    let res = await collection.add({
      token: cookie,
      "token-type": index$1.WifiFlowCookie,
      valid: true,
      update: utils.util.baseDateDes(new Date())
    });
    res = res || {};
    return res.id;
  }
}
async function getFlowCookie() {
  let [err, data] = await getDbCache();
  if (!utils.util.nilValue(err)) {
    return [err, void 0];
  }
  let wifiFlow = void 0;
  if (data) {
    wifiFlow = {
      token: data.token,
      valid: data.valid,
      id: data._id
    };
  }
  return [void 0, wifiFlow];
}
async function initialControl(docId) {
  let [new_err, new_data] = await index.requestNewCookie();
  if (!utils.util.nilValue(new_err)) {
    return [new_err, void 0];
  }
  let updateDocId = await updateCookie(new_data, docId);
  let [req_err, req_data] = await index.requestCardInfo(new_data);
  if (!utils.util.nilValue(req_err)) {
    if (updateDocId) {
      await collection.doc(updateDocId).update({
        valid: false,
        update: utils.util.baseDateDes(new Date())
      });
    }
    return [req_err, void 0];
  }
  return [void 0, req_data];
}
async function getFlowData() {
  let [err, token] = await getFlowCookie();
  if (!utils.util.nilValue(err)) {
    return [err, void 0];
  }
  if (!token || token.valid !== true) {
    return await initialControl(token == null ? void 0 : token.id);
  } else {
    let [req_err, req_data] = await index.requestCardInfo(token.token ?? "");
    if (!utils.util.nilValue(req_err)) {
      if (token.id) {
        await collection.doc(token.id).update({
          valid: false,
          update: utils.util.baseDateDes(new Date())
        });
      }
      return await initialControl(token.id);
    }
    return [void 0, req_data];
  }
}
exports.getFlowData = getFlowData;
